//
//  NetRequestWithCache_JR.m
//  KidReading
//
//  Created by Yinjialiang on 16/2/26.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "NetRequestWithCache_JR.h"
#import <sys/utsname.h>
#import "ConstDefine.h"
@implementation NetRequestWithCache_JR{
    NSString *appVersion;
    NSString *appVersionBundle;
    NSString *deviceName;
    NSString *os_ver;
}

static NetRequestWithCache_JR *singleNetRequestWithCache_JR = nil;

- (instancetype)init
{
    if (self = [super init]) {
        os_ver = [UIDevice currentDevice].systemVersion;
        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
        appVersionBundle = [infoDic objectForKey:@"CFBundleVersion"];
        appVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
        deviceName = [self machineName];
    }
    return self;
}

-(NSString*) machineName
{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString* deviceString = [NSString stringWithCString:systemInfo.machine
                                                encoding:NSUTF8StringEncoding];
    NSString* deviceModel = [[UIDevice currentDevice] model];
    if ([deviceString hasPrefix:deviceModel]) {
        return deviceString;
    }
    return deviceModel;
}

+(NetRequestWithCache_JR *)shareSingle{
    if (singleNetRequestWithCache_JR == nil) {
        singleNetRequestWithCache_JR = [[NetRequestWithCache_JR alloc] init];
    }
    return singleNetRequestWithCache_JR;
}

- (BOOL)isRefSafeForNet
{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    if (uinfo.uid > 0 && uinfo.catoken.length > 0) {
        return YES;
    }
    return NO;
}


-(void)JR_netRequestWithType:(RequestType)requestType Port:(NSString*)port andBaseUrl:(NSString*)baseUrl parameters:(NSDictionary*)dict success:(void (^)(NSDictionary* retDict))success failure:(void (^)(NSError *error))failure{
    if (![self isRefSafeForNet]) {
        failure([[NSError alloc] initWithDomain:@"Error: UserInfo 不完整" code:-1009 userInfo:nil]);
        return;
    }
    NSDictionary *params = [self netRequestAddBaseInfo:dict];
    [[NetRequestWithCahce shareSingle] netRequestWithType:requestType Port:port andBaseUrl:baseUrl parameters:params success:^(NSDictionary *retDict) {
        //请求成功(同步离线数据)
        NSDictionary* dict = retDict[@"retinfo"];
        NSString* msg = retDict[@"msg"];
        NSInteger flag = [retDict[@"flag"] integerValue];
        //
        if (retDict[@"wawaCoin"]) {
            NSInteger currentWaWaCoin = [retDict[@"wawaCoin"] integerValue];
            NSInteger localWaWaCoin = [[WaWaYaYaRewardManager defaultManager] getLocalWaWaCoin];
            BOOL hasLocalWaWaCoin = [[WaWaYaYaRewardManager defaultManager] hasLocalWaWaCoin];
            if (hasLocalWaWaCoin && currentWaWaCoin > localWaWaCoin) {
                [[WaWaYaYaRewardManager defaultManager] addRedPointWithServerRetTure];
            }else if ((currentWaWaCoin >= 0 && currentWaWaCoin < localWaWaCoin) || !hasLocalWaWaCoin){
                [[WaWaYaYaRewardManager defaultManager] updateLocalWaWaCoin:currentWaWaCoin];
            }
        }
        //故事卡数量
        if (retDict[@"storyCardPieceNum"]) {
            [[WaWaYaYaRewardManager defaultManager] updateFragmentStoryCardCount:[retDict[@"storyCardPieceNum"] integerValue] CompletedStoryCardCount:[retDict[@"storyCardNum"] integerValue]];
        }
        //
        if (msg) {
            if (flag != 1001) {
                [[WaitingShow shareSingleShow] showString:msg andAutoHide:YES];
            }
            if (flag == 1001) {//token 过期
                if ([CacheData shareSingle].getUserLoginInfo.uid == [dict[@"userId"] integerValue]) {
                    NSLog(@"token out: // %@",port);
                    [[WaitingShow shareSingleShow] showString:msg andAutoHide:YES];
                    [[DBHelper shareInstance] showTokenOutMsg:msg];
                }
            }
        }
        if (flag == 1) {
            if (dict.count == 0) {
                dict = @{@"flag":@(1)};
            }
            success(dict);
        }else{
            success(nil);
        }
        
    } failure:^(NSError *error) {

        if(failure)failure(error);
        
    }];
}



//不限制五分钟内不请求
-(void)JR_netRequestWithCacheType:(RequestType)requestType Port:(NSString *)port baseUrl:(NSString *)baseUrl parameters:(NSDictionary*)dict  keyID:(NSString *)keyId success:(void (^)(NSDictionary* retDict,BOOL hasCache))success failure:(void (^)(NSError *error,BOOL hasCache))failure cache:(void (^)(NSDictionary * cacheRetDict))cacheBack{
    //
    [self JR_netRequestWithCacheType:requestType Port:port baseUrl:baseUrl parameters:dict keyID:keyId NeedCache:YES success:^(NSDictionary *retDict, BOOL hasCache) {
        if (success) success(retDict, hasCache);
    } failure:^(NSError *error, BOOL hasCache) {
        if (failure) failure(error, hasCache);
    } cache:^(NSDictionary *cacheRetDict) {
        if (cacheBack) cacheBack(cacheRetDict);
    }];
}

//实时请求网络(包含是否缓存参数)
-(void)JR_netRequestWithCacheType:(RequestType)requestType Port:(NSString *)port baseUrl:(NSString *)baseUrl parameters:(NSDictionary*)dict  keyID:(NSString *)keyId NeedCache:(BOOL)isNeedCache success:(void (^)(NSDictionary* retDict,BOOL hasCache))success failure:(void (^)(NSError *error,BOOL hasCache))failure cache:(void (^)(NSDictionary * cacheRetDict))cacheBack{
    if (![self isRefSafeForNet]) {
        failure([[NSError alloc] initWithDomain:@"Error: UserInfo 不完整" code:-1009 userInfo:nil],NO);
        return;
    }
    //添加固定信息
    NSDictionary *params = [self netRequestAddBaseInfo:dict];
    [[NetRequestWithCahce shareSingle] netRequestWithCacheType:requestType Port:port baseUrl:baseUrl parameters:params keyID:keyId successAndIsNeedCache:^BOOL(NSDictionary *retDict, BOOL hasCache) {
        //请求成功(同步离线数据)
        NSDictionary* dict = retDict[@"retinfo"];
        NSString* msg = retDict[@"msg"];
        NSInteger flag = [retDict[@"flag"] integerValue];
        //
        if (retDict[@"wawaCoin"]) {
            NSInteger currentWaWaCoin = [retDict[@"wawaCoin"] integerValue];
            NSInteger localWaWaCoin = [[WaWaYaYaRewardManager defaultManager] getLocalWaWaCoin];
            BOOL hasLocalWaWaCoin = [[WaWaYaYaRewardManager defaultManager] hasLocalWaWaCoin];
            if (hasLocalWaWaCoin && currentWaWaCoin > localWaWaCoin) {
                [[WaWaYaYaRewardManager defaultManager] addRedPointWithServerRetTure];
            }else if ((currentWaWaCoin >= 0 && currentWaWaCoin < localWaWaCoin) || !hasLocalWaWaCoin){
                [[WaWaYaYaRewardManager defaultManager] updateLocalWaWaCoin:currentWaWaCoin];
            }
        }
        //故事卡数量
        if (retDict[@"storyCardPieceNum"]) {
            [[WaWaYaYaRewardManager defaultManager] updateFragmentStoryCardCount:[retDict[@"storyCardPieceNum"] integerValue] CompletedStoryCardCount:[retDict[@"storyCardNum"] integerValue]];
        }
        //
        if (msg) {
            if (flag != 1001) {
                [[WaitingShow shareSingleShow] showString:msg andAutoHide:YES];
            }
            if (flag == 1001) {//token 过期
                if ([CacheData shareSingle].getUserLoginInfo.uid == [dict[@"userId"] integerValue]) {
                    NSLog(@"token out: // %@",port);
                    [[WaitingShow shareSingleShow] showString:msg andAutoHide:YES];
                    [[DBHelper shareInstance] showTokenOutMsg:msg];
                }
                return NO;
            }
        }
        if (flag == 1) {
            if (dict.count == 0) {
                dict = @{@"flag":@(1)};
            }
            success(dict,hasCache);
        }else{
            success(nil,hasCache);
            return NO;
        }
        
        return isNeedCache;
        
    } failure:^(NSError *error, BOOL hasCache) {
        
        if(failure)failure(error,hasCache);
        
    } cache:^(NSDictionary *cacheRetDict) {
        
        NSDictionary* cacheRetinfoDict = cacheRetDict[@"retinfo"];
        if(cacheBack)cacheBack(cacheRetinfoDict);
        
    } timeOut:60];
}




//五分钟不重复请求网络
-(void)JR_netRequestLimitedWithCacheType:(RequestType)requestType Port:(NSString *)port baseUrl:(NSString *)baseUrl parameters:(NSDictionary*)dict  keyID:(NSString *)keyId success:(void (^)(NSDictionary* retDict,BOOL hasCache))success failure:(void (^)(NSError *error,BOOL hasCache))failure cache:(void (^)(NSDictionary * cacheRetDict))cacheBack{
    //
    [self JR_netRequestLimitedWithCacheType:requestType Port:port baseUrl:baseUrl parameters:dict keyID:keyId NeedCache:YES success:^(NSDictionary *retDict, BOOL hasCache) {
        if (success) success(retDict, hasCache);
    } failure:^(NSError *error, BOOL hasCache) {
        if (failure) failure(error, hasCache);
    } cache:^(NSDictionary *cacheRetDict) {
        if (cacheBack) cacheBack(cacheRetDict);
    }];
}

//五分钟不重复请求网络(包含是否缓存参数)
-(void)JR_netRequestLimitedWithCacheType:(RequestType)requestType Port:(NSString *)port baseUrl:(NSString *)baseUrl parameters:(NSDictionary*)dict  keyID:(NSString *)keyId NeedCache:(BOOL)isNeedCache success:(void (^)(NSDictionary* retDict,BOOL hasCache))success failure:(void (^)(NSError *error,BOOL hasCache))failure cache:(void (^)(NSDictionary * cacheRetDict))cacheBack{
    if (![self isRefSafeForNet]) {
        failure([[NSError alloc] initWithDomain:@"Error: UserInfo 不完整" code:-1009 userInfo:nil],NO);
        return;
    }
    //添加固定信息
    NSDictionary *params = [self netRequestAddBaseInfo:dict];
    [[NetRequestWithCahce shareSingle] netRequestWithCacheType:requestType Port:port baseUrl:baseUrl parameters:params keyID:keyId successAndIsNeedCache:^BOOL(NSDictionary *retDict, BOOL hasCache) {
        //请求成功(同步离线数据)
        NSDictionary* dict = retDict[@"retinfo"];
        NSString* msg = retDict[@"msg"];
        NSInteger flag = [retDict[@"flag"] integerValue];
        //
        if (retDict[@"wawaCoin"]) {
            NSInteger currentWaWaCoin = [retDict[@"wawaCoin"] integerValue];
            NSInteger localWaWaCoin = [[WaWaYaYaRewardManager defaultManager] getLocalWaWaCoin];
            BOOL hasLocalWaWaCoin = [[WaWaYaYaRewardManager defaultManager] hasLocalWaWaCoin];
            if (hasLocalWaWaCoin && currentWaWaCoin > localWaWaCoin) {
                [[WaWaYaYaRewardManager defaultManager] addRedPointWithServerRetTure];
            }else if ((currentWaWaCoin >= 0 && currentWaWaCoin < localWaWaCoin) || !hasLocalWaWaCoin){
                [[WaWaYaYaRewardManager defaultManager] updateLocalWaWaCoin:currentWaWaCoin];
            }
        }
        //故事卡数量
        if (retDict[@"storyCardPieceNum"]) {
            [[WaWaYaYaRewardManager defaultManager] updateFragmentStoryCardCount:[retDict[@"storyCardPieceNum"] integerValue] CompletedStoryCardCount:[retDict[@"storyCardNum"] integerValue]];
        }
        //
        if (msg) {
            if (flag != 1001) {
                [[WaitingShow shareSingleShow] showString:msg andAutoHide:YES];
            }
            if (flag == 1001) {//token 过期
                if ([CacheData shareSingle].getUserLoginInfo.uid == [dict[@"userId"] integerValue]) {
                    NSLog(@"token out: // %@",port);
                    [[WaitingShow shareSingleShow] showString:msg andAutoHide:YES];
                    [[DBHelper shareInstance] showTokenOutMsg:msg];
                }
                return NO;
            }
        }
        if (flag == 1) {
            if (dict.count == 0) {
                dict = @{@"flag":@(1)};
            }
            success(dict,hasCache);
        }else{
            success(nil,hasCache);
            return NO;
        }
        
        return isNeedCache;
        
    } failure:^(NSError *error, BOOL hasCache) {
        if(failure)failure(error,hasCache);
    } cache:^(NSDictionary *cacheRetDict) {
        
        NSDictionary* cacheRetinfoDict = cacheRetDict[@"retinfo"];
        if(cacheBack)cacheBack(cacheRetinfoDict);
        
    } timeOut:60 timeLimitedType:TimeLimitedFive_Minutes ParamsIsJson:NO];
}

//清除某个接口的五分钟限制时间
-(void)JR_cleanLastLimitedDateWithPort:(NSString*)port BaseUrl:(NSString*)baseUrl keyID:(NSString*)keyId{
    [[NetRequestWithCahce shareSingle] cleanLastLimitedDateWithPort:port BaseUrl:baseUrl keyID:keyId];
}

- (NSMutableDictionary*)netRequestAddBaseInfo:(NSDictionary*)dict
{
    //添加固定增加信息
    NSMutableDictionary* newDict = [NSMutableDictionary dictionaryWithDictionary:dict];
    [newDict addEntriesFromDictionary:[DataProcessing getSaltInfo]];
    [newDict setObject:[self getUMSuiid] forKey:@"uuid"];
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPad) {
        [newDict setObject:@"pad" forKey:@"deviceType"];
    }else{
        [newDict setObject:@"phone" forKey:@"deviceType"];
    }
    [newDict setObject:@"ios" forKey:@"platform"];
    if(os_ver)[newDict setObject:os_ver forKey:@"osVer"];
    if(appVersionBundle)[newDict setObject:appVersionBundle forKey:@"app_ver_Bundle"];
    if(appVersion)[newDict setObject:appVersion forKey:@"appVer"];
    [newDict setObject:[DataProcessing shareSingle].language forKey:@"client_lang"];
    if(deviceName)[newDict setObject:deviceName forKey:@"deviceName"];
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    if(uinfo.uid)[newDict setObject:@(uinfo.uid).description forKey:@"userId"];
    if(uinfo.catoken)[newDict setObject:uinfo.catoken forKey:@"caToken"];
    [newDict setObject:uinfo.token ? uinfo.token : @"" forKey:@"token"];
    if(uinfo.country_code)[newDict setObject:uinfo.country_code forKey:@"countryCode"];
    if (uinfo.isGuest) {
        [newDict setObject:@(1) forKey:@"isGuest"];
    }else{
        [newDict setObject:@(0) forKey:@"isGuest"];
    }
    if([uinfo isGuest_exp_device]) {
        [newDict setObject:@(0) forKey:@"isDevice"];
    }else {
        [newDict setObject:@(1) forKey:@"isDevice"];
    }
    [newDict setObject:@"2209410" forKey:@"appId"];
    
    return newDict;
}

// getUMSuiid
- (NSString*)getUMSuiid
{
    NSString* udid = [WY3SDKLogin get_idfv];
    if ([udid hasPrefix:@"idfv_"]) {
        return udid;
    }else {
        return [NSString stringWithFormat:@"idfv_%@",udid];
    }
}

@end
